<template>
  <div class="statistics-page">
    <div class="page-header">
      <h2>结算数据统计分析:</h2>
      <el-button type="primary" @click="refreshData">刷新数据</el-button>
    </div>

    <!-- 图表容器 -->
    <div class="chart-container">
      <!-- 结算状态分布饼图 -->
      <div class="chart-item">
        <h3>结算状态分布</h3>
        <div ref="statusPieChart" class="chart" style="width: 100%; height: 400px;"></div>
      </div>

      <!-- 订单数量与金额柱状图 -->
      <div class="chart-item">
        <h3>承运商订单与金额统计</h3>
        <div ref="carrierBarChart" class="chart" style="width: 100%; height: 400px;"></div>
      </div>
    </div>

    <!-- 数据表格（可选，保留原始数据展示） -->
    <div class="data-table">
      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="statementNo" label="对账单号"></el-table-column>
        <el-table-column prop="carrier" label="承运商"></el-table-column>
        <el-table-column prop="settlementStatus" label="结算状态"></el-table-column>
        <el-table-column prop="totalOrders" label="订单总数量"></el-table-column>
        <el-table-column prop="payableAmount" label="应付总金额(元)"></el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { list } from '@/api/tms/complete/all'
import * as echarts from 'echarts'

export default {
  data() {
    return {
      tableData: [],
      loading: false,
      statusPieChart: null,
      carrierBarChart: null
    }
  },
  created() {
    this.fetchData()
  },
  mounted() {
    // 初始化图表
    this.initCharts()
    // 监听窗口大小变化，重绘图表
    window.addEventListener('resize', this.resizeCharts)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts)
    // 销毁图表实例
    if (this.statusPieChart) this.statusPieChart.dispose()
    if (this.carrierBarChart) this.carrierBarChart.dispose()
  },
  methods: {
    // 获取数据
    fetchData() {
      this.loading = true
      list({ pageSize: 1000 }).then(response => { // 获取足够多的数据用于统计
        this.tableData = response.rows || []
        this.loading = false
        this.updateCharts() // 更新图表数据
      }).catch(error => {
        console.error('获取数据失败:', error)
        this.loading = false
        this.$message.error('数据加载失败')
      })
    },

    // 初始化图表
    initCharts() {
      this.statusPieChart = echarts.init(this.$refs.statusPieChart)
      this.carrierBarChart = echarts.init(this.$refs.carrierBarChart)

      // 设置默认图表配置
      this.statusPieChart.setOption({
        tooltip: { trigger: 'item' },
        legend: { top: '5%', left: 'center' }
      })

      this.carrierBarChart.setOption({
        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
        legend: { data: ['订单数量', '应付金额'] },
        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
        xAxis: { type: 'category', data: [] },
        yAxis: [{ type: 'value', name: '订单数量' }, { type: 'value', name: '金额(元)' }]
      })
    },

    // 更新图表数据
    updateCharts() {
      if (!this.tableData.length) return

      // 1. 结算状态分布数据处理
      const statusData = this.tableData.reduce((acc, item) => {
        const status = item.settlementStatus || '未知状态'
        acc[status] = (acc[status] || 0) + 1
        return acc
      }, {})

      // 2. 承运商订单与金额数据处理
      const carrierData = {}
      this.tableData.forEach(item => {
        const carrier = item.carrier || '未知承运商'
        if (!carrierData[carrier]) {
          carrierData[carrier] = { orders: 0, amount: 0 }
        }
        carrierData[carrier].orders += item.totalOrders || 0
        carrierData[carrier].amount += item.payableAmount || 0
      })

      const carriers = Object.keys(carrierData)
      const orderCounts = carriers.map(carrier => carrierData[carrier].orders)
      const amounts = carriers.map(carrier => carrierData[carrier].amount)

      // 更新饼图
      this.statusPieChart.setOption({
        series: [{
          name: '结算状态',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: { show: false, position: 'center' },
          emphasis: { label: { show: true, fontSize: 16 } },
          labelLine: { show: false },
          data: Object.entries(statusData).map(([name, value]) => ({ name, value }))
        }]
      })

      // 更新柱状图
      this.carrierBarChart.setOption({
        xAxis: { data: carriers },
        series: [
          { name: '订单数量', type: 'bar', yAxisIndex: 0, data: orderCounts },
          { name: '应付金额', type: 'line', yAxisIndex: 1, data: amounts, lineStyle: { width: 3 } }
        ]
      })
    },

    // 刷新数据
    refreshData() {
      this.fetchData()
    },

    // 调整图表大小
    resizeCharts() {
      this.statusPieChart.resize()
      this.carrierBarChart.resize()
    }
  }
}
</script>

<style scoped>
.statistics-page {
  padding: 20px;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.chart-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 30px;
}
.chart-item {
  background: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.05);
}
.data-table {
  background: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.05);
}
</style>
